<template>
  <van-form>
    <van-icon name="arrow-left" id="arrow-left" @click="$router.back()"/>
    <div class="title">短信登录</div>

  <van-field
    show-error-message="false"
    v-model="mobile"
    name="mobile"
    placeholder="请输手机号"
    :rules="[{ required: true, },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不对' }]"
  />
  <van-field
  show-error-message="false"
   class="password"
    v-model="code"
    name="code"
    placeholder="请输入验证码"
    :rules="[{ required: true, message: '请输入验证码'},
      { pattern: /^\d{6}$/, message: '验证码是6个数字' }]"
  >
    <template #button>
    <van-button size="small" type="default" class="default"  :disabled="countdown > 0"
          @click="handleSendCode"
        >
          {{ countdown > 0 ? `${countdown}秒后重新发送` : '发送验证码' }}</van-button>
   </template>

  </van-field>
  <div style="margin: 16px;">
    <!-- <van-button round block type="info" native-type="submit">提交</van-button> -->
    <van-button type="primary" native-type="submit" size="large"  color="linear-gradient(to right, #fc6627, #fd504e)" @click="fn">登录</van-button>
  </div>
</van-form>
</template>

<script>
import axios from 'axios'
export default {
  name: 'LoginPage',
  data () {
    return {
      mobile: '',
      code: '',
      countdown: 0, // 倒计时时间
      timerId: null // 定时器 ID
    }
  },
  methods: {
    onSubmit (values) {
      console.log('submit', values)
    },
    async handleSendCode () {
      const res = await axios.get(`http://toutiao.itheima.net/v1_0/sms/codes/${this.mobile}`)
      console.log(res)
      if (this.countdown > 0) {
        return
      }
      this.countdown = 60
      this.timerId = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          clearInterval(this.timerId)
          this.timerId = null
        }
      }, 1000)
    },
    async fn () {
      this.$router.push('/home')
      const res = await axios.post('http://toutiao.itheima.net/v1_0/authorizations', {
        mobile: this.mobile,
        code: this.code
      })
      // console.log(res.data.data.token)
      localStorage.setItem('hm-jky-token', res.data.data.token)
    }
  }
}
</script>

<style lang="less" scoped>
.title{
  font-weight: 700;
  margin-left: 17px;
  margin-bottom: 20px;
  font-size: 22px;
}
#arrow-left{
 color: #9d9d9d;
 font-size: 18px;
 margin-left: 10px;
 margin-top: 15px;
 margin-bottom: 15px;
}
.password{
  color: #C8C9CC;
}
.default{
  border: none;
}
</style>
